package com.cmsz.jiangxm.MyBatisTest.conf;

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import com.github.pagehelper.PageHelper;

@Configuration
@MapperScan("com.cmsz.jiangxm.MyBatisTest.dao")
public class MyBatisConfig {
	
	@Autowired
    private Environment env;
	
	 @Bean
	 public DataSource getDataSource(){
		 Properties props = new Properties();
	     props.put("driverClass", env.getProperty("jdbc.driverClassName"));
	     props.put("url", env.getProperty("jdbc.url"));
	     props.put("username", env.getProperty("jdbc.username"));
	     props.put("password", env.getProperty("jdbc.password"));
	     props.put("initialSize", env.getProperty("jdbc.initialSize"));
	     props.put("minIdle", env.getProperty("jdbc.minIdle"));
	     props.put("maxActive", env.getProperty("jdbc.maxActive"));
	     props.put("maxWait", env.getProperty("jdbc.maxWait"));
	     props.put("useGlobalDataSourceStat", env.getProperty("jdbc.useGlobalDataSourceStat"));
	     try {
	    	 return DruidDataSourceFactory.createDataSource(props);
	     } catch (Exception e) {
	         e.printStackTrace();
	        }
	        return null;
	 }
	 
	 @Bean
	 public SqlSessionFactory sqlSessionFactory(DataSource ds) throws Exception{
		 SqlSessionFactoryBean sfb = new SqlSessionFactoryBean();
	     sfb.setDataSource(ds);
	     //下边两句仅仅用于*.xml文件，如果整个持久层操作不需要使用到xml文件的话（只用注解就可以搞定），则不加
	     sfb.setTypeAliasesPackage(env.getProperty("mybatis.typeAliasesPackage"));
	     sfb.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(env.getProperty("mybatis.mapperLocations")));
	     Interceptor[] plugins = new Interceptor[]{pageHelper()};
	     sfb.setPlugins(plugins);
	     return sfb.getObject();
	 }
	 
	 /**  
      * 分页插件  
      * @param dataSource  
      * @return  
      */
	 @Bean  
     public PageHelper pageHelper() {  
         PageHelper pageHelper = new PageHelper();  
         Properties p = new Properties();  
         p.setProperty("offsetAsPageNum", "true");  
         p.setProperty("rowBoundsWithCount", "true");  
         p.setProperty("reasonable", "true");  
         p.setProperty("returnPageInfo", "check");  
         p.setProperty("params", "count=countSql");  
         pageHelper.setProperties(p);  
         return pageHelper;  
     }
	 
	//事务管理  
     @Bean  
     public PlatformTransactionManager annotationDrivenTransactionManager() {  
         return new DataSourceTransactionManager(getDataSource());  
     }
     
    /////////  下面是druid 监控访问的设置  /////////////////  
     @Bean  
     public ServletRegistrationBean druidServlet() {  
    	 ServletRegistrationBean reg = new ServletRegistrationBean();  
         reg.setServlet(new StatViewServlet());  
         reg.addUrlMappings("/druid/*");  //url 匹配  
         reg.addInitParameter("allow", "127.0.0.1"); // IP白名单 (没有配置或者为空，则允许所有访问)  
         reg.addInitParameter("deny", "192.168.16.111"); //IP黑名单 (存在共同时，deny优先于allow)  
         reg.addInitParameter("loginUsername", env.getProperty("jdbc.druidLoginName"));//登录名  
         reg.addInitParameter("loginPassword", env.getProperty("jdbc.druidPassword"));//登录密码  
         reg.addInitParameter("resetEnable", "false"); // 禁用HTML页面上的“Reset All”功能  
         return reg;  
     }
     
     @Bean(name="druidWebStatFilter")  
     public FilterRegistrationBean filterRegistrationBean() {  
         FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();  
         filterRegistrationBean.setFilter(new WebStatFilter());  
         filterRegistrationBean.addUrlPatterns("/*");  
         filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"); //忽略资源  
         filterRegistrationBean.addInitParameter("profileEnable", "true");  
         filterRegistrationBean.addInitParameter("principalCookieName", "USER_COOKIE");  
         filterRegistrationBean.addInitParameter("principalSessionName", "USER_SESSION");  
         return filterRegistrationBean;  
     } 
}
